package com.pirestupppai.ui.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.pirestupppai.R;
import com.pirestupppai.adapter.PsListAdapter;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.bean.FeedItem;
import com.pirestupppai.bean.UploadFile;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.rxbus.RxBus;
import com.pirestupppai.utils.BitmapUtil;
import com.pirestupppai.utils.ImageIOManager;
import com.pirestupppai.utils.ImageLoadUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.widgets.dialog.ProgressingDialog;
import com.pirestupppai.widgets.dialog.SearchTagDialog;
import com.pirestupppai.widgets.view.FlowTagLayout;
import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static com.pirestupppai.R.id.location_tv;
import static com.pirestupppai.rxbus.RxBus.RXBUS_FINISH_ACTIVITY;
import static com.pirestupppai.rxbus.RxBus.RXBUS_REFRESH_FEED_LIST;

/**
 * 发布页
 *
 * @author: xiaoluo
 * @date: 2017-03-20 15:24
 */
public class ReleaseActivity extends BaseActivity {

    @BindView(R.id.release_btn)
    Button releaseBtn;
    @BindView(R.id.image_layout)
    LinearLayout imageLinear;
    @BindView(R.id.desc_et)
    EditText descEt;
    @BindView(location_tv)
    TextView locationTv;
    @BindView(R.id.tag_layout)
    FlowTagLayout tagLayout;
    @BindView(R.id.video_image)
    ImageView videoImage;
    @BindView(R.id.video_layout)
    RelativeLayout videoLayout;
    @BindView(R.id.parent_layout)
    RelativeLayout parentLayout;

    private int mReleaseType;
    private int mPsType;
    private int mParentId = -1;
    private boolean isReplyNow = false;
    private List<String> mResultList = new ArrayList<>();
    private ArrayList<Integer> mUploadIdList = new ArrayList<Integer>();         // 上传多图返回的id
    private ArrayList<Float> mImageRatioList = new ArrayList<Float>();      // 图片高度/图片宽度
    private ArrayList<Float> mImageScaleList = new ArrayList<Float>();      // 屏幕显示宽度/图片显示宽度
    private List<String> mTagList = new ArrayList<>();                  // 选择的标题

    private ProgressingDialog mDialog;
    private String mVideoPath;
    private String mVideoImagePath;
    private int mUploadCount = 0;
    private static final String DEFAULT_LOCATION = "所在位置";
    private String mLocation = DEFAULT_LOCATION; // 城市
    private double mLongitude = 0;  // 经度
    private double mLatitude = 0;   // 纬度
    private boolean isShowLocation = true;


    private UploadManager mUploadManager;  // 上传

    // 定位
    private AMapLocationClient mLocationClient = null;
    private AMapLocationClientOption mLocationOption = null;

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_release;
    }

    @Override
    protected void initViews() {
        Bundle bundle = getIntent().getExtras();
        mReleaseType = bundle.getInt(Constant.IntentKey.RELEASE_TYPE, Constant.SELECT_TYPE_ASK);
        mPsType = bundle.getInt(Constant.IntentKey.PS_TYPE, PsListAdapter.PS_TYPE_REPLY_NOW);
        mParentId = bundle.getInt(Constant.IntentKey.PARENT_ID, -1);
        isReplyNow = bundle.getBoolean(Constant.IntentKey.IS_REPLY_NOW);
        mResultList = bundle.getStringArrayList(Constant.IntentKey.SELECT_LIST);
        mVideoPath = bundle.getString(Constant.IntentKey.VIDEO_PATH);
        mVideoImagePath = bundle.getString(Constant.IntentKey.VIDEO_IMG);

        descEt.setFocusableInTouchMode(true);
        descEt.requestFocus();
        locationTv.setText(DEFAULT_LOCATION);

        initLabel();
        initImageOrVideo();
        initUpload();
        initLocation();
    }

    /**
     * 初始化定位
     */
    private void initLocation() {
        //初始化client
        mLocationClient = new AMapLocationClient(this.getApplicationContext());
        mLocationOption = getDefaultOption();
        //设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        // 设置定位监听
        mLocationClient.setLocationListener(locationListener);
        mLocationClient.startLocation();
    }

    /**
     * 定位参数配置
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 初始化上传
     */
    private void initUpload() {
        Configuration config = new Configuration.Builder()
                .chunkSize(256 * 1024)  //分片上传时，每片的大小。 默认256K
                .putThreshhold(512 * 1024)  // 启用分片上传阀值。默认512K
                .connectTimeout(10) // 链接超时。默认10秒
                .responseTimeout(60) // 服务器响应超时。默认60秒
                .recorder(null)  // recorder分片上传时，已上传片记录器。默认null
                .recorder(null, null)  // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(Zone.httpsAutoZone) // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();

        mUploadManager = new UploadManager(config);
    }

    /**
     * 初始化视图
     */
    private void initImageOrVideo() {
        if (mReleaseType == Constant.SELECT_TYPE_ASK || mReleaseType == Constant.SELECT_TYPE_WORK) {
            imageLinear.setVisibility(View.VISIBLE);
            videoLayout.setVisibility(View.GONE);

            ImageView firstImage = new ImageView(this);
            ImageView secondImage = new ImageView(this);
            LinearLayout.LayoutParams lpLayoutParams = new LinearLayout.LayoutParams(
                    Utils.dpToPx(mContext, 50), Utils.dpToPx(mContext, 50));
            lpLayoutParams.setMargins(0, 0, Utils.dpToPx(mContext, 6), 0);

            firstImage.setLayoutParams(lpLayoutParams);
            secondImage.setLayoutParams(lpLayoutParams);
            firstImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
            secondImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
            firstImage.setOnClickListener(finishListener);
            secondImage.setOnClickListener(finishListener);

            imageLinear.removeAllViews();
            if (mResultList != null && mResultList.size() == 1) {
                ImageLoadUtil.getInstance().loadImage("file://" + mResultList.get(0), firstImage);
                imageLinear.addView(firstImage);

                if (mReleaseType != Constant.SELECT_TYPE_WORK) {
                    LinearLayout.LayoutParams lpLayoutParamAdd = new LinearLayout.LayoutParams(
                            Utils.dpToPx(mContext, 50), Utils.dpToPx(mContext, 50));
                    lpLayoutParamAdd.setMargins(0, 0, 0, 0);
                    ImageView addImage = new ImageView(this);
                    addImage.setLayoutParams(lpLayoutParamAdd);
                    addImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    addImage.setBackgroundResource(R.drawable.add_photo);
                    imageLinear.addView(addImage);
                    addImage.setOnClickListener(finishListener);
                }
            } else if (mResultList != null && mResultList.size() == 2) {
                ImageLoadUtil.getInstance().loadImage("file://" + mResultList.get(0), firstImage);
                imageLinear.addView(firstImage);
                ImageLoadUtil.getInstance().loadImage("file://" + mResultList.get(1), secondImage);
                imageLinear.addView(secondImage);
            }
        } else {
            imageLinear.setVisibility(View.GONE);
            videoLayout.setVisibility(View.VISIBLE);
            ImageLoadUtil.getInstance().loadImage(mVideoImagePath, videoImage);
        }
    }

    /**
     * 初始化标签
     */
    private void initLabel() {
        tagLayout.removeAllViews();
        final LinearLayout.LayoutParams tagLp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        tagLp.setMargins(Utils.dpToPx(mContext, 0), Utils.dpToPx(mContext, 0),
                Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10));
        final TextView addTag = new TextView(mContext);
        addTag.setText("添加标签 + ");
        addTag.setTextSize(13);
        addTag.setPadding(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 6), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 6));
        addTag.setTextColor(getResources().getColor(R.color.gray_text));
        addTag.setBackgroundResource(R.drawable.selector_edit_save_bg);
        tagLayout.addView(addTag, tagLp);

        addTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTagList.size() >= 8) {
                    addTag.setClickable(false);
                    Utils.showToast("标签最多8个");
                    return;
                }
                SearchTagDialog dialog = new SearchTagDialog(mContext, new SearchTagDialog.OnSearchResultListener() {
                    @Override
                    public void onResult(final String text) {
                        final TextView tag = new TextView(mContext);
                        tag.setText(text);
                        tag.setTextSize(13);
                        tag.setPadding(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 6), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 6));
                        tag.setTextColor(getResources().getColor(R.color.gray_text));
                        tag.setBackgroundResource(R.drawable.selector_search_flow_tag);
                        tag.setClickable(true);
                        tag.setTag(tag.getText().toString());

                        tag.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                tagLayout.removeView(tag);
                                mTagList.remove(text);
                                if (mTagList.size() < 8) {
                                    addTag.setClickable(true);
                                }
                            }
                        });

                        mTagList.add(text);
                        tagLayout.addView(tag, tagLp);
                    }
                });
                dialog.show();
            }
        });
    }

    @Override
    protected void initListeners() {
        releaseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mUploadCount = 0;
                if (TextUtils.isEmpty(descEt.getText().toString().trim())) {
                    Utils.showToast("请输入描述");
                    return;
                }
                if (descEt.getText().toString().trim().length() > 200) {
                    Utils.showToast("字数请不要超过200");
                    return;
                }
                if (mReleaseType == Constant.SELETC_TYPE_VIDEO_ASK || mReleaseType == Constant.SELETC_TYPE_VIDEO_WORK) {
                    Utils.showToast("视频内容!");
                    finish();
                    return;
                }
                releaseBtn.setClickable(false);
                if (mDialog != null && !mDialog.isShowing()) {
                    mDialog.show();
                }

                mImageRatioList.clear();
                mImageScaleList.clear();
                mUploadIdList.clear();
                for (int i = 0; i < mResultList.size(); i++) {
                    Bitmap mDecodeBitmap = BitmapUtil.decodeBitmap(mResultList.get(i));
                    String name = "upload_" + i;
                    // 保存压缩过的bitmap到本地
                    String path = ImageIOManager.getInstance().saveUploadImage(name, mDecodeBitmap);


//                    int imageHeight = mDecodeBitmap.getHeight();
//                    int imageWidth = mDecodeBitmap.getWidth();
//                    float imageRatio = (float) imageHeight / (float) imageWidth;
//
//                    mImageRatioList.add(imageRatio);
//
//                    Resources res = getResources();
//                    float mScale = (float) (Constant.WIDTH_OF_SCREEN - 2 * res
//                            .getDimensionPixelSize(R.dimen.photo_margin))
//                            / imageWidth;
//                    mImageScaleList.add(mScale);

                    if (!TextUtils.isEmpty(path)) {
                        getUploadToken(name, path);
                    }
                }
            }
        });

        locationTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowLocation) {
                    locationTv.setText(DEFAULT_LOCATION);
                    isShowLocation = false;
                } else {
                    if (!TextUtils.isEmpty(mLocation)) {
                        locationTv.setText(mLocation);
                    } else {
                        locationTv.setText(DEFAULT_LOCATION);
                    }

                    isShowLocation = true;
                }
            }
        });

        parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInputPanel();
            }
        });
    }

    @Override
    protected void initLogic() {
        mDialog = new ProgressingDialog(mContext);
        dismissDialog();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    private View.OnClickListener finishListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    };

    /**
     * 定位监听
     */
    private AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    //定位完成的时间
//                    sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                    mLocation = location.getCity();
                    mLongitude = location.getLongitude();
                    mLatitude = location.getLatitude();
                    if (isShowLocation) {
                        locationTv.setText(mLocation);
                    }
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                    if (isShowLocation) {
                        locationTv.setText(mLocation);
                    }
                }
                //定位之后的回调时间
//                sb.append("回调时间: " + Utils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
            } else {
                if (isShowLocation) {
                    locationTv.setText(mLocation);
                }
            }
        }
    };


    /**
     * 获取上传token
     */
    private void getUploadToken(String name, final String path) {
        NetworkRequest.getInstance().getUploadToken(name, this,
                new TupaiSubscriber<UploadFile>(mContext) {
                    @Override
                    protected void requestSuccess(UploadFile uploadFile) {
                        if (TextUtils.isEmpty(uploadFile.getToken())) {
                            return;
                        }
                        uploadToQiniu(uploadFile, path);
                    }

                    @Override
                    protected void requestError(String error) {
                        uploadError(error);
                    }
                });

    }

    /**
     * 上传到七牛
     */
    private void uploadToQiniu(final UploadFile uploadFile, String path) {
        mUploadManager.put(path, uploadFile.getKey(), uploadFile.getToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        if (info.isOK()) {
                            checkUpload(uploadFile.getUpload_id());
                        } else {
                            uploadError("info is no OK");
                        }
                    }
                }, null);
    }

    /**
     * 上传检查
     */
    private void checkUpload(final int upload_id) {
        NetworkRequest.getInstance().checkUpload(upload_id, this,
                new TupaiSubscriber<UploadFile>(mContext) {

                    @Override
                    protected void requestSuccess(UploadFile uploadFile) {
                        if (uploadFile != null) {
                            mUploadCount++;
                            mUploadIdList.add(upload_id);

                            if (mUploadCount == mResultList.size()) {
                                uploadImageData();
                            }
                        } else {
                            uploadError("upload == null");
                        }
                    }

                    @Override
                    protected void requestError(String error) {
                        uploadError(error);
                    }
                });
    }

    /**
     * 上传图片成功后,上传数据
     */
    private void uploadImageData() {

        String releasetype = "ask_ps";
        if (mReleaseType == Constant.SELECT_TYPE_WORK) {
            releasetype = "reply_ps";
        } else if (mReleaseType == Constant.SELECT_TYPE_ASK) {
            releasetype = "ask_ps";
        }

        List<Integer> uploadIds = new ArrayList<>();
        for (int i = 0; i < mUploadIdList.size(); i++) {
            uploadIds.add(mUploadIdList.get(i));
        }

        Map<String, String> locationMap = new HashMap<>();
        if (isShowLocation && mLatitude != 0 && mLongitude != 0 && !mLocation.equals(DEFAULT_LOCATION)) {
            locationMap.put("location", mLocation);
            locationMap.put("location_longitude", String.valueOf(mLongitude));
            locationMap.put("location_latitude", String.valueOf(mLatitude));
        }

        NetworkRequest.getInstance().uploadData(releasetype, descEt.getText().toString(), uploadIds, mTagList, mParentId, mPsType, locationMap, this,
                new TupaiSubscriber<FeedItem>(getApplicationContext()) {
                    @Override
                    protected void requestSuccess(FeedItem jsonObject) {
                        if (jsonObject != null) {
                            Utils.showToast("上传成功");

                            RxBus.getInstance().post(RXBUS_REFRESH_FEED_LIST, "");
                            RxBus.getInstance().post(RXBUS_FINISH_ACTIVITY, "");
                            finish();
                        }
                        dismissDialog();
                    }

                    @Override
                    protected void requestError(String error) {
                        uploadError(error);
                    }
                });
    }

    /**
     * 关闭加载中对话框
     */
    private void dismissDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        releaseBtn.setClickable(true);
    }

    /**
     * 上传失败
     */
    private void uploadError(String error) {
        dismissDialog();
        Utils.showToast("上传失败:" + error);
    }

    private void hideInputPanel() {
        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(descEt.getWindowToken(), 0);
    }

    /**
     * 销毁定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void destroyLocation(){
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }
    }
}
